import Vue from 'vue'
import VueRouter from 'vue-router'
import Store from '@/store'
import { getLocal } from '@/utils/local.js'
import { auInfo } from '@/api/my.js'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    alias: '/login',
    component: () => import('@/views/login/login.vue')
  },
  {
    path: '/home',
    component: () => import('@/views/home/home.vue'),
    redirect: '/home/my',
    children: [
      {
        path: '/home/company',
        component: () => import('@/views/home/company/company.vue'),
        meta: {
          needTab: true
        }
      },
      {
        path: '/home/question',
        component: () => import('@/views/home/question/question.vue'),
        meta: {
          needLogin: true,
          needTab: true
        }
      },
      {
        path: '/home/find',
        component: () => import('@/views/home/find/find.vue'),
        meta: {
          needTab: true
        }
      },
      {
        path: '/home/my',
        component: () => import('@/views/home/my/my.vue'),
        meta: {
          needLogin: true,
          needTab: true
        }
      },
      {
        path: '/home/myInfo',
        component: () => import('@/views/home/my/myInfo.vue'),
        meta: {
          needLogin: true
        }
      },
      {
        path: '/home/editInfo',
        component: () => import('@/views/home/my/editInfo.vue'),
        meta: {
          needLogin: true
        }
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  if (to.meta.needLogin) {
    // 判断是否已经登录
    if (Store.state.isLogin) {
      next()
    } else {
      if (getLocal()) {
        // 有正常的token才发请求
        auInfo()
          .then(res => {
            // 将获取到的用户信息保存起来
            Store.commit('getUserInfo', res.data.data)
            Store.commit('setIsLogin', true)
            // 成功之后才跳转
            next()
          })
          .catch(() => {})
      } else {
        next('/login?redirect=' + to.fullPath)
      }
    }
  } else {
    next()
  }
})
const originalPush = VueRouter.prototype.push

VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
export default router
